﻿<%@ WebHandler Language="C#" Class="RTGS.Web.ajaxhandler.usermanagement.sys_t_user" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;

using RTGS.Library;
using RTGS.Library.DataAccess.UserManagement;
using RTGS.Library.Entities.UserManagement;
using RTGS.Library.Enum;

using RTGS.Web.support;

namespace RTGS.Web.ajaxhandler.usermanagement
{
    public class sys_t_user : RTGS.Web.BaseHandler
    {

        private sysTUserRepo userDal = new sysTUserRepo(ConfigurationManager.ConnectionStrings["Rtgs"].ConnectionString);

        private sysTLogRepo logDal = new sysTLogRepo(ConfigurationManager.ConnectionStrings["Rtgs"].ConnectionString);
        private sysTLog log = new sysTLog();

        private string MethodName = string.Empty;

        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);
    
            MethodName = context.Request.Params["method"];

            context.Response.Clear();
            context.Response.Buffer = true;

            switch (MethodName.ToLower())
            {
                case ("insert"):
                    context.Response.Write(Insert(context));
                    break;
                case ("update"):
                    context.Response.Write(Update(context));
                    break;
                case ("delete"):
                    context.Response.Write(Delete(context));
                    break;
                case ("getdata"):
                    context.Response.Write(GetData(context));
                    break;
                case ("changepassword"):
                    context.Response.Write(UpdatePassword(context));
                    break;
                case ("getexpiredpassword"):
                    context.Response.Write(GetExpiredPassword(context));
                    break;
                case ("getautocomplate"):
                    context.Response.Write(GetAutoComplate(context));
                    break;
                case ("getsamepassword"):
                    context.Response.Write(GetSamePassword(context));
                    break;
                default:
                    // do nothing
                    break;
            }

            context.Response.Flush();
            context.Response.End();

        }

        public override bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #region CRUD Handler

        private string Insert(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();

            sysTUser obj = new sysTUser();

            if(context.Request.Params["user_name"]!=null)
            {
                string userName = context.Request.Params["user_name"].ToString().Trim();
                int checkUser = Convert.ToInt32(userDal.SelectScalar(SQL.Function.Aggregate.Count, sysTUser.Fields.userName, " WHERE LOWER(USER_NAME)= LOWER('"+userName+"')"));

                if (checkUser != 1)
                {
                    bool isActive = context.Request.Params["isactive"] == null ? false : (context.Request.Params["isactive"] == "1" ? true : false);
                    bool isLock = context.Request.Params["islock"] == null ? false : (context.Request.Params["islock"] == "1" ? true : false);

                    obj.email = context.Request.Params["email"];
                    obj.isactive = isActive;
                    obj.islock = isLock;
                    obj.mobile = context.Request.Params["mobile"];
                    obj.password = Helper.CreatePasswordHash(context.Request.Params["password"]);
                    obj.userName = context.Request.Params["user_name"];
                    obj.expiredDays = Convert.ToInt16(context.Request.Params["expireddays"]);
                    obj.expiredDate = DateTime.Now.AddDays(Convert.ToInt16(context.Request.Params["expireddays"]));
                    
                    //expireddays
                   
                    obj.createdDate = DateTime.Now;
                    obj.createdBy = base.UserLoggedIn;

                    if (userDal.Save(obj))
                    {
                        helper.Data = obj;
                        helper.Message = "Data has been saved!";
                        helper.IsSuccess = true;

                        log = new sysTLog();
                        log.logEvent = "Insert User Success";
                        log.logMessage = string.Empty;
                        log.createdBy = base.UserLoggedIn;
                        log.createdDate = DateTime.Now;
                        logDal.Save(log);
                    }
                    else
                    {
                        helper.IsSuccess = false;
                        helper.Message = userDal.GetErrorMessage();

                        log = new sysTLog();
                        log.logEvent = "Insert User Error";
                        log.logMessage = userDal.GetErrorMessage();
                        log.createdBy = base.UserLoggedIn;
                        log.createdDate = DateTime.Now;
                        logDal.Save(log);
                    }
                }
                else
                {
                    helper.Message = " User sudah terdaftar pada aplikasi..!!!";
                }

            }
           

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string Update(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();

            bool isActive = context.Request.Params["isactive"] == null ? false : (context.Request.Params["isactive"] == "1" ? true : false);
            bool isLock = context.Request.Params["islock"] == null ? false : (context.Request.Params["islock"] == "1" ? true : false);

            sysTUser obj = new sysTUser();
            obj.userId = Convert.ToInt32(context.Request.Params["id"]);
            obj.email = context.Request.Params["email"].ToString();
            obj.isactive = isActive;
            obj.islock = isLock;
            obj.mobile = context.Request.Params["mobile"].ToString();
            //dto.PASSWORD = Helper.CreatePasswordHash(context.Request.Params["password"].ToString());
           
            obj.userName = context.Request.Params["user_name"].ToString();
            obj.modifiedDate = DateTime.Now;
            obj.modifiedBy = base.UserLoggedIn;


            obj.expiredDays = Convert.ToInt16(context.Request.Params["expireddays"]);
            obj.expiredDate = DateTime.Now.AddDays(Convert.ToInt16(context.Request.Params["expireddays"]));
                   

            if (userDal.Update(obj))
            {
                helper.Data = obj;
                helper.Message = "Data has been updated!";
                helper.IsSuccess = true;

                log = new sysTLog();
                log.logEvent = "Update User Success";
                log.logMessage = string.Empty;
            }
            else
            {
                helper.IsSuccess = false;
                helper.Message = userDal.GetErrorMessage();

                log = new sysTLog();
                log.logEvent = "Update User Error";
                log.logMessage = userDal.GetErrorMessage();
                             
            }

            log.logSource = "sys_t_user.ashx";
            log.createdBy = base.UserLoggedIn;
            log.createdDate = DateTime.Now;
            logDal.Save(log);  

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string Delete(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();

            bool isSuccess = true;
            string[] ids = context.Request.Params["id"].Split(',');
            foreach (string id in ids)
            {
                int intID = Convert.ToInt32(id);
                
                isSuccess = userDal.Delete(intID);
                if (!isSuccess) break;
            }

            if (isSuccess)
            {
                helper.IsSuccess = true;
                helper.Message = "Data has been deleted!";

                log = new sysTLog();
                log.logEvent = "Delete User Success";
                log.logMessage = string.Empty;
            }
            else
            {
                helper.IsSuccess = false;
                helper.Message = userDal.GetErrorMessage();

                log = new sysTLog();
                log.logEvent = "Delete User Error";
                log.logMessage = userDal.GetErrorMessage();
                               
            }

            log.logSource = "sys_t_user.ashx";
            log.createdBy = base.UserLoggedIn;
            log.createdDate = DateTime.Now;
            logDal.Save(log); 

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string GetData(HttpContext context)
        {
            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? sysTUser.Fields.userName : context.Request.QueryString["sidx"].ToString());

            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());

            string field = ((context.Request.Params["field"]) == null ? string.Empty : context.Request.QueryString["field"].ToString());
            string operand = ((context.Request.Params["operand"]) == null ? string.Empty : context.Request.QueryString["operand"].ToString());
            string value = ((context.Request.Params["value"]) == null ? string.Empty : context.Request.QueryString["value"].ToString());

            string parameters = string.Empty;

            if (!string.IsNullOrEmpty(value))
            {
                field = operand.ToLower().Contains("like") ? "LOWER(" + field + ")" : field;
                field = field.ToLower().Contains("date") ? "CONVERT(char(8), " + field + ", 112)" : field;

                var filter = operand.ToLower().Contains("like") ? "'%" + value.ToLower() + "%'" :
                    field.ToLower().Contains("date") ? "'" + Helper.ToSQLServerDateISO(value) + "'" : "'" + value + "'"; // TextBox Filter

                parameters = " WHERE " + field + " " + operand + " " + filter;
            }

            int totalCount = Convert.ToInt32(userDal.SelectScalar(SQL.Function.Aggregate.Count, sysTUser.Fields.userId, parameters));

            decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
            int totalPages = Convert.ToInt32(dc);

            List<sysTUser> pagedList = userDal.GetList(pageSize, page, sidx, sord, parameters);

            if (!string.IsNullOrEmpty(userDal.GetErrorMessage()))
            {
                log = new sysTLog();
                log.logEvent = "GetData User Error";
                log.logMessage = userDal.GetErrorMessage();
               
            }
            else
            {
                log = new sysTLog();
                log.logEvent = "View Data User Success";
                log.logMessage = string.Empty;
            }

            log.logSource = "sys_t_user.ashx";
            log.createdBy = base.UserLoggedIn;
            log.createdDate = DateTime.Now;
            logDal.Save(log);

            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = pagedList,

            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);
        }

        private string UpdatePassword(HttpContext context)
        {
            
            JSONHelper helper = new JSONHelper();

            int user_id = Convert.ToInt32(context.Request.Params["userid"]);
            string new_password = Helper.CreatePasswordHash(context.Request.Params["password"]);

            sysTUser user = userDal.GetById(user_id);

            //if (new_password == user.password)
            //{
            //    helper.Message = "Password baru tidak boleh sama dengan password lama.!!";
            //    return Newtonsoft.Json.JsonConvert.SerializeObject(helper);
            //}
            
            if (userDal.Update(user_id, new_password, base.UserLoggedIn))
            //if (new_password == "ABV")
            {
                helper.Message = "Password berhasil dirubah..!";
                helper.IsSuccess = true;

                log = new sysTLog();
                log.logEvent = "Change Password Success";
                log.logMessage = string.Empty;
            }
            else
            {
                helper.IsSuccess = false;
                helper.Message = userDal.GetErrorMessage();

                log = new sysTLog();
                log.logEvent = "Change Password Error";
                log.logMessage = userDal.GetErrorMessage();
                
            }

            log.logSource = "sys_t_user.ashx";
            log.createdBy = base.UserLoggedIn;
            log.createdDate = DateTime.Now;
            logDal.Save(log);

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string GetExpiredPassword(HttpContext context)
        {
            var userId = Convert.ToInt32(context.Request.Params["id"]);

            sysTUser user = userDal.GetById(userId);
            string expiredPassword = "false";
            if (user.expiredDate <= DateTime.Now)
            {
                expiredPassword="true";
            }
            
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("{");
            sb.AppendFormat(" {0}expired{0}:{0}{1}{0}", "\"",expiredPassword);
                        
            sb.Append("}");

            if (!string.IsNullOrEmpty(userDal.GetErrorMessage()))
            {
                //sysTLog log = new sysTLog();
                //log.logEvent = "GetData By Id";
                //log.logMessage = userDal.GetErrorMessage();
                //log.logSource = "sys_t_user.ashx";
                //log.createdBy = base.UserLoggedIn;
                //log.createdDate = DateTime.Now;
                //logDal.Save(log);
            }

            return sb.ToString();

        }

        private string GetSamePassword(HttpContext context)
        {
            var userId = Convert.ToInt32(context.Request.Params["id"]);
            string new_password = Helper.CreatePasswordHash(context.Request.Params["password"]);
            
            sysTUser user = userDal.GetById(userId);
            string samepassword = "false";
            if (user.password==new_password)
            {
                samepassword = "true";
            }

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("{");
            sb.AppendFormat(" {0}samepassword{0}:{0}{1}{0}", "\"", samepassword);

            sb.Append("}");

            if (!string.IsNullOrEmpty(userDal.GetErrorMessage()))
            {
                //sysTLog log = new sysTLog();
                //log.logEvent = "GetData By Id";
                //log.logMessage = userDal.GetErrorMessage();
                //log.logSource = "sys_t_user.ashx";
                //log.createdBy = base.UserLoggedIn;
                //log.createdDate = DateTime.Now;
                //logDal.Save(log);
            }

            return sb.ToString();

        }

        public string GetAutoComplate(HttpContext context)
        {

            List<sysTUser> list = userDal.GetList();

            List<sysAutoComplate> result = new List<sysAutoComplate>();
           
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            foreach (sysTUser user in list)
            {

                sysAutoComplate obj = new sysAutoComplate();
                obj.value = user.userId.ToString();
                obj.label = user.userName;

                result.Add(obj);
            }

            
            return Newtonsoft.Json.JsonConvert.SerializeObject(result);//sb.ToString().Substring(0, sb.ToString().Length - 1));
        }

        #endregion

    }
}